package com.bw.sofa_module.detail;

import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewbinding.ViewBinding;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.LogUtils;
import com.bw.adapter_sdk.quick.BaseQuickAdapter;
import com.bw.common.entity.LiveDataEntity;
import com.bw.common.entity.RoomUserEntity;
import com.bw.common.mvvm.view.BaseActivity;
import com.bw.common.utils.ToastShowUtils;
import com.bw.glide_sdk.LoadImage;
import com.bw.network_sdk.videoentity.VideoValuesEntity;
import com.bw.sofa_module.R;
import com.bw.sofa_module.databinding.ActivityDetailBinding;
import com.bw.sofa_module.detail.adapter.DetailAdapter;
import com.bw.sofa_module.detail.entity.RecommentData;
import com.bw.sofa_module.detail.entity.RecommentEntity;
import com.bw.sofa_module.detail.entity.delete.DeleteEntity;
import com.bw.sofa_module.detail.entity.select.RecommentSelectEntity;
import com.bw.umeng_sdk.EventContract;
import com.bw.umeng_sdk.UMengManager;
import com.tb.emoji.Emoji;
import com.tb.emoji.EmojiUtil;
import com.tb.emoji.FaceFragment;
import com.umeng.analytics.MobclickAgent;

import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

@Route(path = "/sofa/videodetail")
public class VideoDetailActivity extends BaseActivity<ActivityDetailBinding,VideoDetailViewModel> implements BaseQuickAdapter.OnItemClickChildListener, FaceFragment.OnEmojiClickListener {

    @Autowired
    Bundle bundle;

    private VideoValuesEntity videoValuesEntity;
    private DetailAdapter detailAdapter;
    private int position = -1;
    private boolean isInput = false;

    @Override
    public View bindLayout() {
        return v.getRoot();
    }

    @Override
    public ViewBinding initBinding() {
        return ActivityDetailBinding.inflate(inflater);
    }

    @Override
    public void initView() {
        ARouter.getInstance().inject(this);
        videoValuesEntity = (VideoValuesEntity) bundle.getSerializable("videoEntity");

        Map<String,Object> eventMap = new HashMap<>();
        eventMap.put("itemtype",videoValuesEntity.itemType);
        eventMap.put("itenid",videoValuesEntity.id);
        UMengManager.getInstance().totalLikedTag(eventMap, EventContract.LIKED_TAG);

        v.detailInclude.detailArtist.setText(videoValuesEntity.author.name);
        v.detailInclude.detailContent.setText(videoValuesEntity.author.description);
        v.detailInclude.detailTagContent.setText(videoValuesEntity.feeds_text);
        LoadImage.LoadCirImg(videoValuesEntity.author.avatar,v.detailInclude.detailArtistImg);

        switch (videoValuesEntity.itemType) {
            case 0:
                v.detailVideoview.setVisibility(View.GONE);
                break;
            case 1:
                v.detailVideoview.setImgUrl(videoValuesEntity.cover);
                v.detailVideoview.setMediaControllerVisibility(View.GONE);
                break;
            case 2:
                v.detailVideoview.setPlayUrl(videoValuesEntity.url,videoValuesEntity.cover);
                v.detailVideoview.start();
                break;
        }

        v.detailInclude.recommentRecycler.setLayoutManager(new LinearLayoutManager(this));
    }

    @Override
    public void initData() {
        v.addRecomment.setOnClickListener(v1->{
            vm.addComment(
                    v.detailInput.getText().toString(),
                    1,
                    videoValuesEntity.cover,
                    videoValuesEntity.itemId,
                    videoValuesEntity.url,
                    1);
        });

        v.detailBrow.setOnClickListener(v1-> {
            if (!isInput){
                v.Container.setVisibility(View.VISIBLE);
                FaceFragment faceFragment = FaceFragment.Instance();
                getSupportFragmentManager().beginTransaction().add(R.id.Container,faceFragment).commit();
                isInput = true;
            }else{
                v.Container.removeAllViews();
                v.Container.setVisibility(View.INVISIBLE);
                isInput = false;
            }
        });
    }

    @Override
    public String getClassNames() {
        return this.getClass().getName();
    }

    @Override
    protected void handleMessage(LiveDataEntity entity) {
        switch (entity.action) {
            case START_VIEW_MODEL:
                RecommentSelectEntity recommentSelectEntity = (RecommentSelectEntity) entity.data.get(LiveDataEntity.LiveDataType.ENTITY);
                detailAdapter.setNewInstance(recommentSelectEntity.data.data);
                break;
            case DELETE_COMMENT:
                DeleteEntity deleteEntity = (DeleteEntity) entity.data.get(LiveDataEntity.LiveDataType.ENTITY);
                if (deleteEntity.data.data.result && position != -1){
                    detailAdapter.remove(position);
                }else {
                    ToastShowUtils.toastShort("删除失败");
                }
                break;
            case USERID:
                RoomUserEntity roomUserEntity = (RoomUserEntity)entity.data.get(LiveDataEntity.LiveDataType.ENTITY);
                detailAdapter = new DetailAdapter(roomUserEntity.data.data.userId);
                detailAdapter.setOnItemClickChildListener(this);
                v.detailInclude.recommentRecycler.setAdapter(detailAdapter);
                vm.selectComment(videoValuesEntity.itemId,10,roomUserEntity.data.data.userId);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        vm.initData();
    }

    @Override
    public void onItemClickChild(RecyclerView.Adapter adapter, int id, int position) {
        if (adapter instanceof DetailAdapter){
            this.position = position;
            DetailAdapter detailAdapter = (DetailAdapter) adapter;
            RecommentData recommentData = detailAdapter.getData().get(position);
            vm.requestDelete(recommentData.commentId,recommentData.itemId);
        }
    }

    @Override
    public void onEmojiDelete() {
        String text = v.detailInput.getText().toString();
        if (text.isEmpty()) {
            return;
        }
        if ("]".equals(text.substring(text.length() - 1, text.length()))) {
            int index = text.lastIndexOf("[");
            if (index == -1) {
                int action = KeyEvent.ACTION_DOWN;
                int code = KeyEvent.KEYCODE_DEL;
                KeyEvent event = new KeyEvent(action, code);
                v.detailInput.onKeyDown(KeyEvent.KEYCODE_DEL, event);
                displayTextView();
                return;
            }
            v.detailInput.getText().delete(index, text.length());
            displayTextView();
            return;
        }
        int action = KeyEvent.ACTION_DOWN;
        int code = KeyEvent.KEYCODE_DEL;
        KeyEvent event = new KeyEvent(action, code);
        v.detailInput.onKeyDown(KeyEvent.KEYCODE_DEL, event);
        displayTextView();
    }

    private void displayTextView() {
        try {
            EmojiUtil.handlerEmojiText(v.detailInput, v.detailInput.getText().toString(), this);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onEmojiClick(Emoji emoji) {
        if (emoji != null) {
            int index = v.detailInput.getSelectionStart();
            Editable editable = v.detailInput.getEditableText();
            if (index < 0) {
                editable.append(emoji.getContent());
            } else {
                editable.insert(index, emoji.getContent());
            }
        }
        displayTextView();
    }
}
